React.js is a powerful JavaScript library for building user interfaces, especially for single-page applications where data needs to be dynamically updated without reloading the whole page. Let's go over some of the key fundamentals of React.js to get you started with building modern, responsive interfaces.
Core of React: React applications are built using components, which are reusable, self-contained pieces of code that represent a part of the user interface.
Types of Components:
Example:
function Welcome() {
return <h1>Hello, World!</h1>;
}
Syntax Extension: JSX allows you to write HTML-like syntax within JavaScript. React then compiles this down to JavaScript.
Embedding Expressions: You can embed JavaScript expressions within JSX using {}.
Example:
const element = <h1>Hello, {user.name}</h1>;
Passing Data: Props allow you to pass data from parent to child components. Props are immutable, meaning they cannot be modified by the child component.
Example:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Using the component
<Welcome name="John" />
Component State: State is a built-in object that holds dynamic data that can change over time. Unlike props, the state is mutable.
Using useState Hook (for functional components):
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Event Handling: Events are handled in a similar way to standard HTML but with JSX, you use camelCase naming conventions and pass functions as event handlers.
Example:
function Button() {
function handleClick() {
console.log('Button clicked');
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
Class Components Only: Lifecycle methods allow you to hook into certain points during a component's lifecycle (mounting, updating, unmounting).
Common Lifecycle Methods:
For Functional Components, React provides useEffect for similar functionality:
import { useEffect } from 'react';
function Example() {
useEffect(() => {
console.log('Component mounted');
return () => {
console.log('Component unmounted');
};
}, []); // Empty array means this runs only on mount/unmount
return <div>Hello World</div>;
}
Displaying Content Conditionally: Use JavaScript's conditional operators (if, ternary, etc.) within JSX to render elements based on conditions.
Example:
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}
Rendering Lists: Use the map() method to render arrays of data.
Keys: Assign a unique key prop to each list item to help React identify which items have changed, added, or removed.
Example:
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
)}
</ul>
);
}
Controlled Components: Forms in React typically use "controlled components" where form data is handled by the component's state.
Example:
function NameForm() {
const [name, setName] = useState('');
function handleChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
alert('A name was submitted: ' + name);
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
Client-Side Routing: React Router allows navigation between different pages without refreshing the whole page.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
);
}
useState: For managing local component state.
useEffect: For handling side effects like data fetching, subscriptions, etc.
useContext: For accessing global data without passing props down the component tree.
Example of useState and useEffect:
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((seconds) => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Seconds: {seconds}</p>;
}
Inline Styles: Use JavaScript objects to define inline styles in JSX.
Styled Components or CSS Modules: For more complex styling, you can use libraries like styled-components or CSS modules.
Example (inline styles):
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray'
};
function StyledDiv() {
return <div style={divStyle}>Styled Div</div>;
}
React.js is all about component-based architecture and reactive data handling. By mastering components, state, props, and hooks, you can efficiently build modern, responsive user interfaces for your web applications.